package com.xiaochun.hxhj;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.widget.LinearLayout;

import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.adapter.FreeReadRecyclerViewAdapter;
import com.bean.FreeReadListBean;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.myview.CustomProgressDialog;
import com.myview.PullLoadMoreRecyclerView;
import com.util.ExitAppUtil;
import com.util.InfoEventMessage;
import com.util.MyLog;
import com.util.RequestManager;
import com.util.ToastUtils;

import org.greenrobot.eventbus.Subscribe;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

public class FreeReadListActivity extends BaseActivity {


    private PullLoadMoreRecyclerView freeread_data;
    private FreeReadRecyclerViewAdapter adapter;
    private LinearLayoutManager layoutManager;
    private View loadMoreShopView;
    private View notMoreShopView;
    private List<FreeReadListBean.DataBeanX.DataBean> booklist = new ArrayList<>();
    private List<FreeReadListBean.DataBeanX.DataBean> booklisttemp = new ArrayList<>();
    private CustomProgressDialog customProgressDialog;
    private int page = 1;
    private int pagecount = 30;
    private View bottomView;
    private LinearLayout loadLlay;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        customProgressDialog = new CustomProgressDialog(context, "", R.style.CommProgressDialog);
        WindowManager.LayoutParams params = customProgressDialog.getWindow().getAttributes();
        params.alpha = 0.7f;//取值为0-1之间  0是全透明，1是不透明
        params.dimAmount = 0f;   //取值为0-1之间  1是全黑
        customProgressDialog.getWindow().setAttributes(params);
        customProgressDialog.show();
    }

    @Override
    protected void initListener() {
        freeread_data.setOnPullLoadMoreListener(new PullLoadMoreRecyclerView.PullLoadMoreListener() {
            @Override
            public void onRefresh() {
                page = 1;
                getData();
            }

            @Override
            public void onLoadMore() {
//                page++;
//                getData();


                if (booklisttemp.size() >= pagecount) {
                    page++;
                    getData();
                }else{
                    freeread_data.setPullLoadMoreCompleted();

                }
            }

            @Override
            public void onScrollChanged(int heightTotal) {

            }

            @Override
            public void onScrollState(int type) {

            }
        });
        adapter.setOnItemClickListener(new FreeReadRecyclerViewAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(int position) {
                int id = booklist.get(position).getId();
                String if_pay = booklist.get(position).getIf_pay();

                if ("1".equals(if_pay)){
                    //需要支付
                    Intent intent = new Intent(context, BuyBookActivity.class);
                    intent.putExtra("id",id+"");
                    startActivity(intent);
                }else if ("0".equals(if_pay)){
                    //不需要付费
                    String token = getUserInfo("token");
                    if ("".equals(token)){
                        Intent intent = new Intent(context,LoginActivity.class);
                        startActivity(intent);
                    }else {
                        Intent intent = new Intent(context, FreeSpeedActivity.class);
                        intent.putExtra("id", id + "");
                        startActivity(intent);
                    }
                }
            }
        });

    }

    @Override
    protected int initLayout() {
        return R.layout.activity_freereadlist;
    }

    @Override
    protected void initView() {
        changeTitle("速读训练");
//        saveNoticeList("name","王冰寒");
        freeread_data = findViewById(R.id.freeread_data);
        adapter = new FreeReadRecyclerViewAdapter(booklist, context, myapp);
        adapter.setHasStableIds(true);
        setHeader(freeread_data);
        freeread_data.setAdapter(adapter);
        freeread_data.setGridLayout(3);
        freeread_data.setRefreshing(true);
        layoutManager = (LinearLayoutManager) freeread_data.getLayoutManager();
//        GridLayoutManager gridLayoutManager = homedataRecycleView.getGridLayoutManager();
        freeread_data.cancleAnimal();
        loadMoreShopView = View.inflate(context, R.layout.item_moredata, null);
        notMoreShopView = View.inflate(context, R.layout.item_nodata, null);
        initTopView();
        GridLayoutManager gridLayoutManager = new GridLayoutManager(context, 3);

        //通过isTitle的标志来判断是否是title
        gridLayoutManager.setSpanSizeLookup(new GridLayoutManager.SpanSizeLookup() {
            @Override
            public int getSpanSize(int position) {
                int itemViewType = adapter.getItemViewType(position);
                if (itemViewType == 6){
                    return 3;
                }else{
                    return 1;
                }
            }
        });
        gridLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        freeread_data.setGridLayout3(gridLayoutManager);

    }
    /**
     * 初始化头部控件
     */
    private void initTopView() {


        //加载更多
        loadLlay = (LinearLayout) bottomView.findViewById(R.id.llay_load);
    }

    @Override
    protected void onResume() {
        super.onResume();
        page = 1;
        getData();
    }

    /**
     * 设置头部布局
     *
     * @param view
     */
    private void setHeader(PullLoadMoreRecyclerView view) {

        //底部加载更多
        bottomView = LayoutInflater.from(context).inflate(R.layout.main_bottom, view, false);
        bottomView.setBackgroundResource(R.color.colorFAFAFA);
        adapter.setBottomView(bottomView);
    }

    @Override
    protected void initData() {

    }
    private void getData() {

        String token = sharedPreferences.getString("token", "");
        String url = myapp.getWebConfig() + "/api/speed/getList";
        HashMap<String, String> paramsMap = new HashMap<>();
        paramsMap.put("token", token+"");
        paramsMap.put("page", page+"");
        paramsMap.put("limit", pagecount+"");
        MyLog.e("免费速读训练列表","token="+token);
        RequestManager.getInstance(context).requestAsyn(url, RequestManager.TYPE_POST_FORM, paramsMap, new RequestManager.ReqCallBack() {
            @Override
            public void onReqSuccess(Object result) {
                MyLog.e("code--result", result.toString());
                Message msg = new Message();
                try {
                    JSONObject jsonObject = new JSONObject(result.toString());
                    if (jsonObject.getString("code").equals("0")) {
                        msg.obj = jsonObject.getString("msg");
                        msg.arg1 = 0;
                        handler.sendMessage(msg);
                        return;
                    }
                    JSONObject data = jsonObject.getJSONObject("data");


                    JSONArray databook = data.getJSONArray("data");
                    booklisttemp.clear();
                    booklisttemp = new Gson().fromJson(databook.toString(), new TypeToken<List<FreeReadListBean.DataBeanX.DataBean>>() {
                    }.getType());

                    msg.arg1 = 2;
                    handler.sendMessage(msg);
                } catch (JSONException e) {
                    e.printStackTrace();
                    msg.arg1 = 1;
                    handler.sendMessage(msg);
                }
            }

            @Override
            public void onReqFailed(String errorMsg) {
                if (errorMsg.equals("未登录")) {
                    Message msg = new Message();
                    msg.arg1 = 11;
                    handler.sendMessage(msg);
                } else {
                    Message msg = new Message();
                    msg.arg1 = 12;
                    handler.sendMessage(msg);
                }
            }
        });
    }
    public Handler handler = new Handler() {

        @SuppressLint("HandlerLeak")
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.arg1) {
                case 0:
                    if (customProgressDialog != null) {
                        if (customProgressDialog.isShowing()) {
                            customProgressDialog.dismiss();
                        }
                    }
                    freeread_data.setPullLoadMoreCompleted();
                    String obj = (String) msg.obj;
                    ToastUtils.show(obj);
                    break;
                case 1:
                    if (customProgressDialog != null) {
                        if (customProgressDialog.isShowing()) {
                            customProgressDialog.dismiss();
                        }
                    }
                    ToastUtils.show(R.string.net_error);
                    freeread_data.setPullLoadMoreCompleted();
                    break;
                case 2:
                    if (customProgressDialog != null) {
                        if (customProgressDialog.isShowing()) {
                            customProgressDialog.dismiss();
                        }
                    }
                    if (page == 1){
                        booklist.clear();
                    }
                    booklist.addAll(booklisttemp);
                    adapter.setDatas(booklist);
                    freeread_data.setPullLoadMoreCompleted();
                    if (booklisttemp.size() == 0){
                        page--;
                    }
                    loadLlay.removeAllViews();
                    if (booklisttemp.size() < pagecount){
                        if (page > 1){
                            loadLlay.addView(notMoreShopView);
                        }
                    }else{
                        loadLlay.addView(loadMoreShopView);
                    }
                    break;
                case 3:


                    break;
                case 4:

                    break;
                case 11:
                    if (customProgressDialog != null) {
                        if (customProgressDialog.isShowing()) {
                            customProgressDialog.dismiss();
                        }
                    }
                    sharedPreferences.edit().putString("user_id","").commit();
                    sharedPreferences.edit().putString("username","").commit();
                    sharedPreferences.edit().putString("nickname","").commit();
                    sharedPreferences.edit().putString("mobile","").commit();
                    sharedPreferences.edit().putString("avatar","").commit();
                    sharedPreferences.edit().putString("score","").commit();
                    sharedPreferences.edit().putString("student_id","").commit();
                    sharedPreferences.edit().putString("is_bind_wx","").commit();
                    sharedPreferences.edit().putString("token","").commit();
                    sharedPreferences.edit().putString("is_agent","").commit();
                    sharedPreferences.edit().putString("vip_expire","").commit();
                    sharedPreferences.edit().putString("is_vip","").commit();
                    finish();
                    break;
                case 12:
                    if (customProgressDialog != null) {
                        if (customProgressDialog.isShowing()) {
                            customProgressDialog.dismiss();
                        }
                    }
                    break;
            }
        }
    };

    @Subscribe
    public void onEventMainThread(InfoEventMessage event) {
        String paymessage = event.getMessage();
        //0失败   1成功

        if ("设备ID已更新退出登录".equals(paymessage)){
            String type = event.getType();
            ExitAppUtil.getInstance().popbyexit(type,context,FreeReadListActivity.this,freeread_data);
//            popbyexit(type);
        }


    }

}
